package com.anjiplus.template.gaea.business.modules.inf.runner;

import com.anjiplus.template.gaea.business.modules.inf.app.dao.entity.GaeaInfAppRelation;
import com.anjiplus.template.gaea.business.modules.inf.app.dao.entity.InfAppEntity;
import com.anjiplus.template.gaea.business.modules.inf.app.service.GaeaInfAppRelationService;
import com.anjiplus.template.gaea.business.modules.inf.app.service.InfAppService;
import com.anjiplus.template.gaea.business.modules.inf.constant.InfAppStatusEnum;
import com.anjiplus.template.gaea.business.modules.inf.constant.InfCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ultrajiaming
 * @since 2021/3/23 9:43
 */
@Component
public class InfApplicationRunner implements ApplicationRunner {
    // 初始化标识的值
    public static final String INIT_FLAG = "1";
    // 初始化标识存在时间
    public static final Long INIT_FLAG_TIMEOUT = 30L;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GaeaInfAppRelationService infAppRelationService;

    @Autowired
    private InfAppService infAppService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        BoundValueOperations<String, String> valueOps = stringRedisTemplate.boundValueOps(InfCacheKey.INIT_FLAG);
        String initFlag = valueOps.get();
        if (null != initFlag && INIT_FLAG.equals(initFlag)) {
            // 已经初始化过了
            return;
        }
        valueOps.set(INIT_FLAG, INIT_FLAG_TIMEOUT, TimeUnit.MINUTES);
        // 初始化appid——appSecret
        initAppSecret();
        // 初始化接口——appId
        initInfApp();
    }

    private void initInfApp() {
        List<GaeaInfAppRelation> infAppRelationList = infAppRelationService.list(Wrappers.emptyWrapper());
        Map<String, List<String>> infAppMap = infAppRelationList.stream().collect(Collectors.groupingBy(GaeaInfAppRelation::getInfName,
                Collectors.mapping(GaeaInfAppRelation::getAppId, Collectors.toList())));
        if (!CollectionUtils.isEmpty(infAppMap)) {
            Set<String> keys = stringRedisTemplate.keys(InfCacheKey.AUTHORIZED_APP + "*");
            stringRedisTemplate.delete(keys);
            for (Map.Entry<String, List<String>> entry : infAppMap.entrySet()) {
                String infName = entry.getKey();
                List<String> appIdList = entry.getValue();
                String infAppKey = InfCacheKey.AUTHORIZED_APP + infName;
                stringRedisTemplate.opsForSet()
                        .add(infAppKey, appIdList.toArray(new String[appIdList.size()]));
            }
        }
    }


    /**
     * 初始化appid appsecret
     **/
    private void initAppSecret() {
        List<InfAppEntity> infAppList = infAppService.list(Wrappers.<InfAppEntity>lambdaQuery()
                .eq(InfAppEntity::getStatus, InfAppStatusEnum.USEFUL.getValue()));
        if (infAppList != null && !infAppList.isEmpty()) {
            // 删除
            Set<String> keys = stringRedisTemplate.keys(InfCacheKey.APP_SECRET + "*");
            stringRedisTemplate.delete(keys);

            ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
            for (InfAppEntity infApp : infAppList) {
                String appSecretKey = InfCacheKey.APP_SECRET + infApp.getAppId();
                valueOps.set(appSecretKey, infApp.getAppSecret());
            }

        }
    }

}
